package com.hsq.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


public class SocketTCP02Server {
    public static void main(String[] args) throws IOException {
        //1.在本机监听9999端口，等待连接
        //注意：要求本机没有其他服务在监听端口9999
        //这个ServerSocket 可以通过accept返回多个Socket[多个客户端连接服务器并发]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端口监听，等待连接");
        //等待连接,当客户端没有连接端口9999时，程序会阻塞
        Socket socket = serverSocket.accept();
        System.out.println("Server socket = " + socket.getClass());
        InputStream inputStream = socket.getInputStream();
        //字符流读取
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String read = bufferedReader.readLine();
        System.out.println(read);
        //同时给client也发送信息
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(outputStream));
        bufferedWriter.write("Hello Client 字符流");
        //另一种结束标志
        bufferedWriter.newLine();
        //设置结束标志
//        socket.shutdownOutput();

        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        inputStream.close();
        System.out.println("Srever exit");
    }
}
